import imaplib
import os, sys, threading
import logging
from django.conf import settings


class MailFetcher():
    
    mailserver = settings.MAILSERVER
    username = settings.MAILUSER
    password = settings.MAILPASSWORD
    logfile = settings.DAEMON_LOGFILE

    connection = imaplib.IMAP4_SSL(mailserver)
    mailrecords = {}

    logging.basicConfig(filename=logfile, format='[%(asctime)s]: %(message)s', level=logging.DEBUG, datefmt="%m/%d/%Y %I:%M:%S %p")
    logger = logging.getLogger('tqd.log')
    logger.propagate = True


    def login(self):
        """
        Try to login in as the given user & password combo
        """
        try:
            self.connection.login(self.username, self.password)
            self.logger.info("Connected to mailbox at: %s" % self.username)
        except Exception as e:
            self.logger.info("Connection to mailbox failed! Error: %s" % e)


    def logout(self):
        """
        close connection to mailserver then logout.
        """
        
        self.connection.close()
        self.connection.logout()


    def fetch(self):
        """
        Fetch all unseen mail from the mailserver and return it in a dictionary.
        """
        self.mailrecords = {}
        self.connection.select('INBOX')
        typ, data = self.connection.search(None, "UNSEEN")
        mbox_stats = self.connection.status('INBOX', '(MESSAGES RECENT UNSEEN)')
        self.logger.info(mbox_stats)
        total = len(data[0].split())
        count = 0
        self.logger.info("Beginning Mail Retrieval Operations: %s items." % total)
        for item in data[0].split():
            self.logger.info("%s" % item)
            count += 1
            typ, data = self.connection.fetch(item, '(RFC822)')
            self.mailrecords[item] = data[0][1]
            if count >= 1250:
                break
        self.logger.info("Returning records")
        return self.mailrecords

    def purge(self):
        """
        Rolls through and flags seen items as deleted, then expunges them.
        """
        conn = self.connection
        conn.select('INBOX')
        typ, data = conn.search(None, "SEEN")
        num = len(data[0].split())
        if num < 1:
            return
        self.logger.info("Beginning Threaded Purge Ops.")
        self.logger.info("Purging %s emails." % num)
        for item in data[0].split():
            conn.store(item, "+FLAGS", '(\\Deleted)')
        self.logger.info("Mail purge ops complete.")
        conn.expunge()

    
     
